package csvIO;

import java.io.IOException;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

public class CsvIO {

	public CsvObject readCSV(String filePath, boolean hasHeader)
			throws IOException {
		CsvReader reader = new CsvReader(filePath);
		CsvObject object = new CsvObject();
		int rowLength = -1;

		if (hasHeader) {
			reader.readHeaders();
			object.setHeaders(reader.getHeaders());
			rowLength = object.getRowLength();
		}

		while (reader.readRecord()) {
			if (rowLength < 0) {
				rowLength = reader.getColumnCount();
			}
			CsvRow row = new CsvRow(rowLength);
			row.setValues(reader.getValues());
			object.addRow(row);
		}

		reader.close();

		return object;
	}

	public void writeCSV(String filePath, CsvObject csvObject)
			throws IOException {
		CsvWriter writer = new CsvWriter(filePath);

		writeCsvObject(writer, csvObject);
	}

	public void writeCsvObject(CsvWriter writer, CsvObject object)
			throws IOException {
		
		if(object.isEmpty()){
			throw new IllegalArgumentException("The csv object provided as parameter is empty");
		}
		
		if(object.hasHeaders()){
			writer.writeRecord(object.getHeaders());
		}

		
		int count = object.getRowsCount();

		for (int i = 0; i < count; i++) {
			writer.writeRecord(object.getRow(i).getValues());
		}

		writer.close();
	}

}
